package com.zjitc.utils;


import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
import java.util.UUID;

import javax.servlet.http.Cookie;

/**
 * Create By IntelliJ IDEA
 *
 * @author:
 * @create-Time: 2017/11/6  15:11
 */
public class Utils {
    /**
     * 随机获取一个uuid，通用唯一的识别码(Universally Unique Identifier)
     *
     * @return uuid的string类型
     */
    public static String getUUID() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    /**利用MD5进行加密
     * @param password  待加密的字符串
     * @return 加密后的字符串
     * @throws NoSuchAlgorithmException  没有这种产生消息摘要的算法
     * @throws UnsupportedEncodingException
     */
    public static String encoderByMd5(String password)
            throws NoSuchAlgorithmException, UnsupportedEncodingException {
        try {
            //得到一个信息摘要器
            MessageDigest digest = MessageDigest.getInstance("md5");
            digest.update(password.getBytes());

            return new BigInteger(1, digest.digest()).toString(32);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static Cookie getCookieByName(String name,Cookie[] cookies){
        if(cookies != null){
            for (Cookie c: cookies) {
                if(name.equals(c.getName())){
                    return c;
                }
            }
        }
        return null;
    }


    /**
     * 随机生成快递单号
     * @return
     */
    public static String code(){
        String s = "0123456789";
        Integer ta =10;
        Random random = new Random();

        String msg = "";
        for (int i = 0; i < ta; i++) {
            int index = random.nextInt(10);
            String content = String.valueOf(s.charAt(index));
            msg += content;
            double theta = random.nextInt(45) * Math.PI / 180;
        }
        return msg;
    }
}
